package PrjConf

import (
	"errors"
	"flag"
	"gitee.com/ymofen/supervalue"
)

var (
	cmdflag_app_id, cmdflag_app_type, cmdflag_api_url *string
)

func check_conf_read_env() error {
	if cmdflag_api_url != nil && len(*cmdflag_api_url) > 0 {
		CONFIG_CONF_API_SVR_URL = *cmdflag_api_url
	}
	if len(CONFIG_CONF_API_SVR_URL) == 0 {
		return errors.New("缺少[CONFIG_CONF_API_SVR_URL]参数")
	}

	if len(CONFIG_CONF_APP_ID) == 0 {
		if cmdflag_app_id != nil {
			CONFIG_CONF_APP_ID = *cmdflag_app_id
		}

		if len(CONFIG_CONF_APP_ID) == 0 {
			return errors.New("缺少[CONFIG_CONF_APP_ID]参数")
		}
	}

	if len(CONFIG_CONF_APP_TYPE) == 0 {
		if cmdflag_app_type != nil {
			CONFIG_CONF_APP_TYPE = *cmdflag_app_type
		}
	}

	return nil

}

func CmdFlagPreapareApiSvrConf() {
	cmdflag_app_id = flag.String("appid", "", "")
	cmdflag_app_type = flag.String("apptype", "", "")
	cmdflag_api_url = flag.String("apiurl", "", "")
}

func ReloadApiSvrConf() (error, *wrapper.SuperValue) {
	err := check_conf_read_env()
	if err != nil {
		return err, nil
	}

	err, str := ReadConfigFromApiSvr(CONFIG_CONF_APP_ID, CONFIG_CONF_APP_TYPE)
	if err != nil {
		return err, nil
	} else {
		rval, err := wrapper.NewSVFromBuf([]byte(str))
		return err, rval
	}
}

func ReloadApiSvrConfByCmd() (error, *wrapper.SuperValue) {
	err := check_conf_read_env()
	if err != nil {
		return nil, nil
	}

	if cmdflag_app_id != nil {
		err, str := ReadConfigFromApiSvr(*cmdflag_app_id, *cmdflag_app_type)
		if err != nil {
			return err, nil
		} else {
			rval, err := wrapper.NewSVFromBuf([]byte(str))
			return err, rval
		}
	} else {
		return nil, nil
	}
}
